﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CreateIdentityScreen.cs" company="">
//   
// </copyright>
// <summary>
//   In this screen the user create new profiles.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

/*
 * Author: Juan Mompean Esteban
 * Created: 6-12-2011
 */
namespace ITU_vs_Zombies.Menu.Screens
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    using ITU_vs_Zombies.Graphics;
    using ITU_vs_Zombies.UsersInfo;

    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Content;
    using Microsoft.Xna.Framework.Graphics;
    using Microsoft.Xna.Framework.Input;

    /// <summary>
    /// In this screen the user create new profiles.
    /// </summary>
    public class CreateIdentityScreen : GameScreen
    {
        #region Constants and Fields

        /// <summary>
        /// The cols.
        /// </summary>
        private const int Cols = 4;

        /// <summary>
        /// The rows.
        /// </summary>
        private const int Rows = 3;

        /// <summary>
        /// The background texture.
        /// </summary>
        private Texture2D backgroundTexture;

        /// <summary>
        /// The content.
        /// </summary>
        private ContentManager content;

        /// <summary>
        /// The font.
        /// </summary>
        private SpriteFont font;

        /// <summary>
        /// The image selected.
        /// </summary>
        private string imageSelected;

        /// <summary>
        /// The matrix.
        /// </summary>
        private MatrixContainer matrix;

        /// <summary>
        /// The text box texture.
        /// </summary>
        private Texture2D textBoxTexture;

        /// <summary>
        /// The user name.
        /// </summary>
        private string userName;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="CreateIdentityScreen"/> class.
        /// </summary>
        public CreateIdentityScreen()
        {
            this.imageSelected = null;
            this.userName = string.Empty;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// The activate.
        /// </summary>
        /// <param name="instancePreserved">
        /// The instance preserved.
        /// </param>
        public override void Activate(bool instancePreserved)
        {
            if (instancePreserved)
            {
                return;
            }

            if (this.content == null)
            {
                this.content = new ContentManager(this.ScreenManager.Game.Services, "Content");
            }

            this.backgroundTexture = this.content.Load<Texture2D>(@"background");
            this.textBoxTexture = this.content.Load<Texture2D>(@"blank");
            this.font = this.content.Load<SpriteFont>(@"fonts\small");
            IEnumerable<string> files = Directory.EnumerateFileSystemEntries(
                this.content.RootDirectory + @"\Profiles", "player*");

            var filesShort = new List<string>(files.Count());
            filesShort.AddRange(
                from file in files
                let tempFile = file.Remove(file.LastIndexOf('.'))
                select tempFile.Substring(file.LastIndexOf('\\') + 1));

            var list = new List<Tuple<string, Texture2D>>(files.Count());
            list.AddRange(
                from file in filesShort
                let texture = this.content.Load<Texture2D>(@"Profiles\" + file)
                select new Tuple<string, Texture2D>(file, texture));

            this.matrix = new MatrixContainer(list, Rows, Cols);
            this.matrix.LoadContent(this.content);
            this.matrix.EnterPressed += this.EnterPressed;
        }

        /// <summary>
        /// The draw.
        /// </summary>
        /// <param name="gameTime">
        /// The game time.
        /// </param>
        public override void Draw(GameTime gameTime)
        {
            Viewport viewport = this.ScreenManager.GraphicsDevice.Viewport;
            var fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height);
            this.ScreenManager.SpriteBatch.Begin();
            this.ScreenManager.SpriteBatch.Draw(this.backgroundTexture, fullscreen, Color.White);
            if (this.imageSelected == null)
            {
                this.matrix.Draw(viewport.Width, viewport.Height, this.ScreenManager.SpriteBatch);
            }
            else
            {
                var postionRectangle = new Vector2((viewport.Width / 2) - 40, (viewport.Height / 2) - 10);
                var textBoxRectangle = new Rectangle((int)postionRectangle.X, (int)postionRectangle.Y, 80, 20);
                this.ScreenManager.SpriteBatch.Draw(this.textBoxTexture, textBoxRectangle, Color.White);
                this.ScreenManager.SpriteBatch.DrawString(this.font, this.userName, postionRectangle, Color.Black);
            }

            this.ScreenManager.SpriteBatch.End();
        }

        /// <summary>
        /// The enter pressed.
        /// </summary>
        /// <param name="name">
        /// The name.
        /// </param>
        public void EnterPressed(string name)
        {
            this.imageSelected = name;
        }

        /// <summary>
        /// The handle input.
        /// </summary>
        /// <param name="gameTime">
        /// The game time.
        /// </param>
        /// <param name="input">
        /// The input.
        /// </param>
        public override void HandleInput(GameTime gameTime, InputState input)
        {
            var escape = new InputAction(new[] { Keys.Escape }, true);
            var letters = new[]
                {
                    Keys.A, Keys.B, Keys.C, Keys.D, Keys.E, Keys.F, Keys.G, Keys.H, Keys.I, Keys.J, Keys.K, Keys.L, Keys.M
                    , Keys.N, Keys.O, Keys.P, Keys.Q, Keys.R, Keys.S, Keys.T, Keys.U, Keys.V, Keys.W, Keys.X, Keys.Y, 
                    Keys.Z
                };
            var back = new InputAction(new[] { Keys.Back }, true);
            var enter = new InputAction(new[] { Keys.Enter }, true);
            this.matrix.Move(input);

            foreach (Keys key in letters.Where(input.IsNewKeyPress))
            {
                this.userName += key.ToString();
            }

            while (this.font.MeasureString(this.userName).Length() > 80)
            {
                this.userName = this.userName.Remove(this.userName.Length - 2);
            }

            if (back.Evaluate(input))
            {
                this.userName = this.userName.Remove(
                    (int)MathHelper.Clamp(this.userName.Length - 1, 0, 80), 
                    (int)MathHelper.Clamp(1, 0, this.userName.Length));
            }

            if (enter.Evaluate(input) && this.userName.Length != 0)
            {
                Dictionary<string, string> profiles = Profiles.LoadProfiles();
                if (!profiles.ContainsKey(this.userName))
                {
                    profiles.Add(this.userName, this.imageSelected);
                }

                Profiles.StoreProfiles(profiles);
            }

            if (!escape.Evaluate(input) && (!enter.Evaluate(input) || this.userName.Length == 0))
            {
                return;
            }

            this.ExitScreen();
        }

        /// <summary>
        /// The unload.
        /// </summary>
        public override void Unload()
        {
            this.content.Unload();
        }

        #endregion
    }
}